package cn.tedu.csmall.passport.ex.handler;

import cn.tedu.csmall.passport.ex.ServiceCode;
import cn.tedu.csmall.passport.ex.ServiceException;
import cn.tedu.csmall.passport.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult<Void> handleServiceException(ServiceException e){
        log.debug("处理ServiceException，serviceCode={}，message={}", e.getCode(),e.getMessage());
        return JsonResult.fail(e);
    }
    @ExceptionHandler
    public JsonResult<Void> handleBindException(BindException e){
        log.debug("处理BindException");
        Integer serviceCode= ServiceCode.ERR_BAD_REQUEST.getValue();
        StringBuilder messageBuilder=new StringBuilder();
        List<FieldError> fieldErrorList=e.getFieldErrors();
        for(FieldError fieldErrors:fieldErrorList){
            messageBuilder.append(fieldErrors.getDefaultMessage());
        }
        return JsonResult.fail(serviceCode,messageBuilder.toString());
    }
    @ExceptionHandler
    public JsonResult<Void> handleConstraintValidationException(ConstraintViolationException e){
        log.debug("处理ConstraintViolationException");
        Integer serviceCode=ServiceCode.ERR_BAD_REQUEST.getValue();

        StringBuilder messageBuilder=new StringBuilder();
        Set<ConstraintViolation<?>> constraintViolations=e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation:constraintViolations){
            messageBuilder.append(constraintViolation.getMessage());
        }
        String message=messageBuilder.toString();
        return JsonResult.fail(serviceCode,message);
    }
    @ExceptionHandler({
            InternalAuthenticationServiceException.class,
            BadCredentialsException.class
    })
    public JsonResult<Void> handleAuthenticationException(AuthenticationException e) {
        log.debug("处理AuthenticationException");
        log.debug("异常类型：{}", e.getClass().getName());
        log.debug("异常信息：{}", e.getMessage());
        Integer serviceCode = ServiceCode.ERR_UNAUTHORIZED.getValue();
        String message = "登录失败，用户名或密码错误！";
        return JsonResult.fail(serviceCode, message);
    }
    @ExceptionHandler
    public JsonResult<Void> handleDisableException(DisabledException e){
        log.debug("处理DisableException");
        Integer serviceCode=ServiceCode.ERR_UNAUTHORIZED_DISABLE.getValue();
        String message="登陆失败，此账号已禁用";
        return JsonResult.fail(serviceCode,message);
    }
    @ExceptionHandler
    public JsonResult<Void> handleAccessDeniedHandlerException(AccessDeniedException e){
        log.debug("处理AccessDeniedHandlerException");
        Integer serviceCode=ServiceCode.ERR_FORBIDDEN.getValue();
        String message="请求失败，当前帐号无权限";
        return JsonResult.fail(serviceCode,message);
    }
    @ExceptionHandler
    public JsonResult<Void> handleThrowable(Throwable e){
        log.debug("处理Throwable");
        e.printStackTrace();

        Integer serviceCode=99999;
        String message="运行出现错误";
        return JsonResult.fail(serviceCode,message);
    }
}
